var AldeasInfantiles = angular.module("AldeasInfantiles", []);

AldeasInfantiles.controller("Persons", function($scope, $http, $timeout) {

  $scope.countries = []; //Array with all registred countries in the database
  $scope.persons = []; //Array with all registred users in the database
  $scope.hiddenClass = "hidden"; //Used to show or hide the error message in the UI
  $scope.alertClass = ""; //Used to display a message in the UI
  $scope.errorMessage = ""; //Used to change the class of the message div in the UI
  $scope.person = {}; //Donor object
  $scope.selectedCountry = ""; //Selected donor country value

  //Requests all countries
  $scope.requestCountries = function () {
    $http({
          async: false,
          method: 'POST', 
          url: currentPath + 'countries/returncountries/'
        }).
        success(function(data) {
          $scope.countries = data;
          $scope.selectedCountry = data[0].id_pais;
        }).
        error(function(data, status) {
          console.log(e.message);
        });
  };

  //Receives the id of an user to get the information from the DB
  $scope.getPersonById = function (persona) {
    var id = persona.id_persona;
    $http({
            method: 'POST', 
            url: currentPath + 'persons/returnpersonbyid/' + id
        }).
        success(function(data) {
          $scope.person.personid = data[0].id_persona;
          $scope.person.personname = data[0].ds_nombre;
          $scope.person.personlast1 = data[0].ds_primer_apellido;
          $scope.person.personlast2 = data[0].ds_segundo_apellido;
          $scope.person.personphone = data[0].ds_telefono;
          $scope.person.personothers = data[0].ds_otros;
          $scope.selectedCountry = 1;
          $('#modal-persons').modal('hide');
        }).
        error(function(data, status) {
           console.log(e.message);
        });
  };

  //Displays all persons in the UI
  $scope.showPersons = function () {
    $http({
            method: 'POST', 
            url: currentPath + 'persons/returnallpersons/'
        }).
        success(function(data) {
          $scope.persons = data;
        }).
        error(function(data, status) {
           console.log(e.message);
        });
  };

  $scope.getParams = function ($person) {
    $params = $.param({
      'personid': $person.personid,
      'personname': $person.personname,
      'personlast1': $person.personlast1,
      'personlast2': $person.personlast2,
      'personphone': $person.personphone,
      'personothers': $person.personothers,
      'personcountry': $scope.selectedCountry
    })
    $scope.savePerson($params);
  };

  //Saves the user information in the database
  $scope.savePerson = function ($params) {
    $http({
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            url: currentPath + 'persons/saveperson/',
            method: 'POST',
            data: $params,
            
        }).
        success(function(data, status) {
          console.log(data);
          if(data.response == "success"){
            $scope.errorMessage = "Datos guardatos correctamente";
            $scope.hiddenClass = "";
            $scope.alertClass = "alert-success";
            $scope.resetForm();
          }else if(data.response == "incomplete_form"){
            $scope.hiddenClass = "";
            $scope.alertClass = "alert-danger";
            $scope.errorMessage = "Debes escribir todos los datos del formulario.";
          }else if(data.response == "failed"){
            $scope.hiddenClass = "";
            $scope.alertClass = "alert-danger";
            $scope.errorMessage = "Algo fallo al guardar los datos, intentalo de nuevo.";
          }
        }).
        error(function(data, status) {
          $scope.hiddenClass = "";
          $scope.errorMessage = data;
        });
  };

  $scope.resetForm = function() {
    $scope.person.personid = "";
    $scope.person.personname = "";
    $scope.person.personlast1 = "";
    $scope.person.personlast2 = "";
    $scope.person.personphone = "";
    $scope.person.personothers = "";
    $scope.selectedCountry = 1;
    $timeout(countUp, 5000);
  };

  var countUp = function() {
    $scope.hiddenClass = "hidden";
  }

  $scope.setDefaultSettings = function () {
    $scope.requestCountries(); 
    //$scope.requestTypeUsers();
    //$scope.adduserstate = 1;
  }

  $scope.setDefaultSettings();

});